import { defineStore } from 'pinia';
import { to } from 'await-to-js';
import type { BannerList } from '@/views/Home/components/api';
import { getBannerList } from '@/views/Home/components/api';
import type { CategoryList, GoodsItem } from '@/views/Category/components/api';
import { getHomeList, getNewGoodList } from '@/views/Category/components/api';
import type { CartItem, GoodsDetail } from '@/views/Goods/components/api';
import request from '@/utils/request';
import {OrderItem} from "@/views/Member/Order/components/api";

// 定义 Store 时建议遵循命名规范 useXxxStore
const useCartStore = defineStore('cart', () => {
  const categoryList = ref<Array<CategoryList>>([]);
  const bannerList = ref<Array<BannerList>>([]);
  const newGoodsList = ref<Array<GoodsItem>>([]);

  /**
   * 加入购物车
   * @param data
   */
  const addCart = async (data: OrderItem) => {
    return await to(
      request({
        url: '/wms/order/pcCart',
        method: 'post',
        data: data
      })
    );
  };

  /**
   * 获取购物车列表
   */
  const getCartList = async (): Promise<GoodsItem[]> => {
    if (bannerList.value.length > 0) {
      return bannerList.value;
    }
    const [code, res] = await to(getBannerList());
    if (res) {
      bannerList.value = res.rows;
      return bannerList.value;
    }
    return [];
  };

  /**
   * 删除/清空购物车商品
   */
  const deleteCart = async (): Promise<GoodsItem[]> => {
    if (newGoodsList.value.length > 0) {
      return newGoodsList.value;
    }
    const [code, res] = await to(
      request({
        url: '/wms/order',
        method: 'post'
      })
    );
    if (res) {
      newGoodsList.value = res.rows;
      return newGoodsList.value;
    }
    return [];
  };

  /**
   * 修改购物车商品-修改选中-修改数量
   */
  const updateCart = async (): Promise<GoodsItem[]> => {
    if (newGoodsList.value.length > 0) {
      return newGoodsList.value;
    }
    const [code, res] = await to(getNewGoodList());
    if (res) {
      newGoodsList.value = res.rows;
      return newGoodsList.value;
    }
    return [];
  };

  /**
   * 购物车全选/取消全选
   */
  const updateCartAllSelected = async (): Promise<GoodsItem[]> => {
    if (newGoodsList.value.length > 0) {
      return newGoodsList.value;
    }
    const [code, res] = await to(getNewGoodList());
    if (res) {
      newGoodsList.value = res.rows;
      return newGoodsList.value;
    }
    return [];
  };

  /**
   * 清空购物车
   */
  const clearCart = async (): Promise<GoodsItem[]> => {
    if (newGoodsList.value.length > 0) {
      return newGoodsList.value;
    }
    const [code, res] = await to(getNewGoodList());
    if (res) {
      newGoodsList.value = res.rows;
      return newGoodsList.value;
    }
    return [];
  };

  return {
    categoryList,
    bannerList,
    newGoodsList,
    addCart
  };
});

// 默认导出
export default useCartStore;
